package com.xiekong.rpc.listener;

import com.xiekong.rpc.annotation.RpcService;
import com.xiekong.rpc.server.RpcServer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.Map;

/**
 * RpcServer 启动监听，用于web容器启动服务
 *
 * @author XieKong
 */
public class RpcServerListener implements ApplicationListener<ContextRefreshedEvent> {
    private RpcServer rpcServer;

    public RpcServerListener(RpcServer rpcServer) {
        this.rpcServer = rpcServer;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        final ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
        /**
         * 起一个线程去启动netty，防止阻塞主线程。
         */
        new Thread() {
            @Override
            public void run() {
                try {
                    // 获取所有带有RpcService注解的Spring Bean
                    Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(RpcService.class);
//                    Map<String, Object> serviceMap = new HashMap<String, Object>();
//                    if (MapUtils.isNotEmpty(serviceBeanMap)) {
//                        for (Object serviceBean : serviceBeanMap.values()) {
//                            String interfaceName = serviceBean.getClass().getAnnotation(RpcService.class).value().getName();
//                            serviceMap.put(interfaceName, serviceBean);
//                        }
//                    }
                    rpcServer.setServiceMap(serviceBeanMap);
                    rpcServer.startup();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
